/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Servlet.user;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ObjectNotFoundException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import server.entity.Photo;
import server.process.ProcessBeanLocal;

/**
 *
 * @author Hoang
 */
public class download extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        ServletOutputStream sos = response.getOutputStream();
        BufferedInputStream bis = null;
        {
            Photo photo = null;
            try {
                int imgid;
                try{
                imgid = Integer.parseInt(request.getParameter("id"));
                }catch (Exception ex){
                    response.sendError(response.SC_NOT_FOUND);
                    return;
                }
                Context ctx = new InitialContext();
                ProcessBeanLocal local = (ProcessBeanLocal) ctx.lookup("ProcessLocalJNDI");
                photo = local.getPhotobyID(imgid);
                local.downloadPhoto(imgid);
                HttpSession session = request.getSession();
                String username = (String) session.getAttribute("username");
                ServletContext sc = session.getServletContext();
                if (photo.getCategory().getAdmin()==false){
                    if (!photo.getRegisteredUser().getUsername().equals(username)){
                        response.sendError(response.SC_FORBIDDEN);
                    }
                }

                //allow download
                ServletConfig config = getServletConfig();
                String RealPath = config.getServletContext ().getRealPath ("/");
                String serverFile = photo.getServerFile();
                File f = new File(RealPath + "\\" + serverFile);
                response.setHeader("Content-Disposition", "attachment; filename=\"" + f.getName() + "\"");
                response.setContentLength((int) f.length());
                response.setContentType("application/octet-stream");
                FileInputStream fis = new FileInputStream(f);
                bis = new BufferedInputStream(fis);
                int readbyte = 0;
                while ((readbyte = bis.read()) != -1) {
                    sos.write(readbyte);
                }
            } catch (ObjectNotFoundException ex) {
                Logger.getLogger(download.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NamingException ex) {
                Logger.getLogger(download.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if (sos != null) {
                    sos.close();
                }
                if (bis != null) {
                    bis.close();
                }
            }
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
